package org.kfive.nova.thread;

import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/*
* CyclicBarrierExample.java
* Created  by  lizhanwu
* Created on 2016-6-1 19:39
*/
public class CyclicBarrierExample {

    private final static int WORKER_NUM = 5;

    private boolean done = false;

    private CyclicBarrier barrier;

    public CyclicBarrierExample(){
        this.barrier = new CyclicBarrier(WORKER_NUM, new Runnable() {
            public void run() {
                done = true;
                System.out.println(Thread.currentThread().getName()+" 等待数："+barrier.getNumberWaiting());
            }
        });
    }

    class CaculationThread implements Runnable{

        private Integer index;

        private CyclicBarrier barrier;

        public CaculationThread(CyclicBarrier barrier,Integer index){
            this.barrier = barrier;
            this.index = index;
        }

        public void run() {
            try {
                System.out.println(Thread.currentThread().getName()+" sleep :"+1000*index);
                Thread.sleep(1000*index);
                System.out.println(Thread.currentThread().getName()+" end");
                barrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }

    public void run(){
        for (int i=1;i<=WORKER_NUM;i++){
            new Thread(new CaculationThread(this.barrier,i)).start();
        }
        while (!done){
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" 等待数："+barrier.getNumberWaiting());
        }
        System.out.println(Thread.currentThread().getName()+" end");
    }

    public static void main(String[] args) {
        CyclicBarrierExample example = new CyclicBarrierExample();
        example.run();
    }

}
